import ble from '../../utils/bluetooth';
Page({
  // switch开关
  switchChange(e) {
    if (e.detail.value) {
      this.setData({
        checked: true
      })
      this.openBluetoothAdapter()
    } else {
      wx.hideLoading()
      this.setData({
        checked: false,
        discovery: false,
        devices: ''
      })
      ble.closeBluetoothAdapter()
    }
  },
  async openBluetoothAdapter() {
    // 初始化蓝牙模块
    wx.showLoading({
      title: '初始化模块中',
    })
    let res = await ble.openBluetoothAdapter()
    if (res.ok) {
      // 获取蓝牙适配器状态
      wx.showLoading({
        title: '获取适配器状态',
      })
      res = await ble.getBluetoothAdapterState()
      if (res.ok) {
        wx.hideLoading()
        // 搜索设备
        this.setData({
          discovery: true
        })
        ble.startBluetoothDevicesDiscovery(cb => {
          console.log('搜索到的设备：', cb)
          this.setData({
            devices: cb
          })
        })
      } else {
        wx.hideloading()
        this.setData({
          checked: false,
        })
      }
    } else {
      wx.hideLoading()
      console.log(res)
      this.setData({
        checked: false,
      })
    }
  },

  // 弹出菜单
  async showAction(e) {
    e = e.currentTarget.dataset
    let {
      devices
    } = this.data
    console.log(e)
    let res = await wx.showActionSheet({
      itemList: [`连接到${devices[e.index].name}`, '重命名此设备'],
    })
    // res.tapIndex == 0时，连接到设备
    if (res.tapIndex == 0) {
      // 停止设备搜索
      ble.stopBluetoothDevicesDiscovery()
      wx.showLoading({
        title: '正在连接',
      })
      this.setData({
        discovery: false
      })
      res = await ble.createBLEConnection(e.deviceid)
      console.log(res)
      if (res.ok) {
        ble.getBLEDeviceServices()
        devices.forEach((item, index) => {
          if (item.deviceid == e.deviceid) {
            item.hasConnected = true
          } else {
            item.hasConnected = false
          }
        });

        this.setData({
          devices
        })
        wx.showToast({
          title: '连接成功',
        })

        // 获取蓝牙低功耗设备所有服务 (service)及某个服务中所有特征 (characteristic)
        // await ble.getBLEDeviceServices()

        // 启用蓝牙低功耗设备特征值变化时的 notify 功能
        // ble.notifyBLECharacteristicValueChange()

        // 监听连接状态变化
        ble.onBLEConnectionStateChange(res => {
          console.log('res', res)
          let index = devices.findIndex(item => item.deviceId == res.deviceId)
          if (index != -1) {
            this.setData({
              [`devices[${e.index}].hasConnected`]: false
            })
          }
        })
        setTimeout(() => {
          this.tongbushijian()
        }, 3000)
      } else {
        wx.showToast({
          title: '连接失败',
          icon: 'error'
        })
      }
    }
    // 重命名蓝牙设备
    else if (res.tapIndex == 1) {
      // let res = await ble.writePrescriptiveDirective()
    }
  },
  async tongbushijian() {
    //同步时间
    let timData = ['0x54', '0x49', '0x4d']
    let thisTime = []
    thisTime.push(parseInt(new Date().getFullYear().toString().substring(2, 4)))
    thisTime.push(parseInt(new Date().getMonth() + 1))
    thisTime.push(parseInt(new Date().getDate()))
    thisTime.push(parseInt(new Date().getHours()))
    thisTime.push(parseInt(new Date().getMinutes()))
    thisTime.push(parseInt(new Date().getSeconds()))

    for (const i in thisTime) {
      timData[parseInt(i) + 3] = '0x' + formatNumber(thisTime[i].toString(16))
    }
    let res = await ble.writePrescriptiveDirective(timData)
    console.log('发送同步时间数据', timData)
    console.log('同步时间', res)
  },
  //断开与低功耗蓝牙设备的连接
  async closeBLEConnection() {
    e = e.currentTarget.dataset
    let res = await ble.closeBLEConnection()
    if (res.ok) {
      this.setData({
        [`devices[${e.index}].hasConnected`]: false
      })
    }
  },
})

function sleep(delay) {
  var start = (new Date()).getTime();
  while ((new Date()).getTime() - start < delay) {
    continue;
  }
}

function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}